
// https://blog.csdn.net/Govern66/article/details/115682072?utm_medium=distribute.pc_aggpage_search_result.none-task-blog-2~aggregatepage~first_rank_v2~rank_aggregation-3-115682072.pc_agg_rank_aggregation&utm_term=react%E5%8A%A8%E6%80%81%E7%94%9F%E6%88%90%E8%B7%AF%E7%94%B1&spm=1000.2123.3001.4430
import React from "react";
import RouteWrapper from './RouteWrapper';
import {
  Switch,
  Route,
  Redirect,
  withRouter
} from "react-router-dom";
import routesConfig, { IFMenuBase, IFMenu } from './config';

import AllComponents from '../pages/';

const Router = (props: any) => {

  const createMenu = (r: any ) => {

    const requireLogin = (component: React.ReactElement) => {
      // const permits = getPermits();
      const hasToken = localStorage.getItem('token') || '';
      if(!hasToken) {
        return <Redirect to={'/login'} />;
      }
      return component;
    };

    const route = (r: IFMenuBase) => {
      const Component = r.component && AllComponents[r.component];
        return (
            <Route
                key={r.route || r.path}
                exact
                path={r.route || r.path}
                render={(props: any) => {
                    // 重新包装组件
                    const wrapper = (
                        <RouteWrapper {...{ ...props, Comp: Component, route: r }} />
                    );
                    return requireLogin(wrapper);
                }}
            />
        );
    };

    const subRoute = (r: IFMenu): any =>
        r.children && r.children.map((subR: IFMenu) => (subR.children ? subRoute(subR) : route(subR)));

    return r.component ? route(r) : subRoute(r);
  };

  const createRoute = (key: string) => {
    return routesConfig[key].map(createMenu)
  };

  return (
    <Switch>
      { Object.keys(routesConfig).map(path => createRoute(path))}
      {/* {getAsyncMenus().map(createMenu)}*/}
      <Route render={() => <Redirect to="/404" />} /> 
    </Switch>
  );
};

export default withRouter(Router);
